<?php

namespace Services\Upload;

use Common\Model\Oss\OssFileModel;
use Services\BaseService;

class OssFileService extends BaseService
{

    /** @var OssFileModel $ossFileModel */
    private $ossFileModel;

    public function __construct()
    {
        $this->ossFileModel = new OssFileModel();
    }

    public static function getOssUrl($absolutePath = '')
    {
        if(empty($absolutePath)){
            return $absolutePath;
        }
        $ossConfig = get_oss_config();
        if (substr($absolutePath, 0, 1) === '/') {
            return arr_get($ossConfig,'domain').$absolutePath;
        }else{
            return arr_get($ossConfig,'domain').'/'.$absolutePath;
        }

    }

    public function getFileByMd5($md5 = ''){
        $info = $this->ossFileModel->where(['md5'=>$md5])->find();
        if($info){
            $info['path'] = self::getOssUrl(arr_get($info,'path'));
            $info['url'] = arr_get($info,'path');
        }
        return $info??[];
    }

    public function add(){
        $saveData = [
            'user_id' => $this->getParam('user_id',0),
            'name' => $this->getParam('name',''),
            'module' => $this->getParam('module',''),
            'path' => $this->getParam('path',''),
            'suffix' => $this->getParam('suffix',''),
            'size' => $this->getParam('size',0),
            'sha1' => $this->getParam('sha1',''),
            'mime' => $this->getParam('mime',''),
            'driver' => $this->getParam('driver',''),
            'ext' => $this->getParam('ext',''),
            'created_at' => $this->getParam('created_at',date('Y-m-d H:i:s')),
            'updated_at' => $this->getParam('updated_at',date('Y-m-d H:i:s')),
        ];
        $insertId = $this->ossFileModel->add($saveData);
        if($insertId){
            $saveData['path'] = self::getOssUrl($saveData['path']);
            $saveData['url'] = arr_get($saveData,'path');
            $saveData['id'] = $insertId;
        }
        return $saveData;
    }

    /**
     * 获取附件列表
     * @param array $where
     * @param string $order
     * @param int $pagesize
     * @param int $pagenum
     * @return array
     */
    public function lists($where = [],$order = '',$pagesize = 1,$pagenum = 10){
        $startnum = ($pagesize - 1)*$pagenum;
        $where = $where;
        if(empty($order)) $order = 'id Desc';
        $data_list = $this->ossFileModel
            ->where($where)
            ->order($order)
            ->page($startnum, $pagenum)
            ->select();
        return $data_list?$data_list:[];
    }
}
